import Taro from "@tarojs/taro"
import Http from "./http"

const globalData = {}
const tokenName = "sessionId"
export function setHttpUrls(key: string, val: number) {
  globalData[key] = val
}

export function getHttpUrls(key: string) {
  return globalData[key] || 0
}
export function cleanQueryParams(path) {
  return path.split("?")[0]
}

export function getHeaderHeight() {
  return new Promise(resolve => {
    Taro.getSystemInfo({
      success: function (res: any) {
        if (res.statusBarHeight > 20) {
          resolve(res.statusBarHeight)
        } else {
          resolve(20)
        }
      },
    })
  })
}

export function getPageHeight() {
  return new Promise(resolve => {
    Taro.getSystemInfo({
      success: function (res: any) {
        resolve(res.windowHeight)
      },
    })
  })
}

export function getPlatform() {
  return new Promise(resolve => {
    Taro.getSystemInfo({
      success: function (res: any) {
        resolve(res.platform)
      },
    })
  })
}

export function setCurrentTokenName(name: string) {
  return Taro.setStorageSync("token_name", name)
}

export function getToken() {
  const token = Taro.getStorageSync("sessionId")
  return token
}

function base64Decode(base64) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
  let decoded = ""

  let buffer = 0
  let bits = 0

  for (let i = 0; i < base64.length; i++) {
    const char = base64.charAt(i)
    const charIndex = chars.indexOf(char)

    if (charIndex === -1) {
      continue // 忽略非法字符
    }

    buffer = (buffer << 6) | charIndex
    bits += 6

    if (bits >= 8) {
      decoded += String.fromCharCode((buffer >> (bits - 8)) & 255)
      bits -= 8
    }
  }

  return decoded
}

export function tokenIsValidate() {
  const token = getToken() // jwt
  return !!token
}

export function applyToken(token) {
  if (token) {
    Taro.setStorageSync(tokenName, `Bearer ${token}`)
  }
}

export function clearUser() {
  Taro.removeStorageSync(tokenName)
  Taro.removeStorageSync("user")
}

export function setLoginUser(user: any) {
  Taro.setStorageSync("user", user)
}

export function getUser() {
  const user = Taro.getStorageSync("user")
  return user
}

export function checkIsLogin() {
  if (tokenIsValidate()) {
    return true
  }
  Taro.showToast({
    title: "请先登录",
    icon: "none",
    duration: 1500,
  })
  setTimeout(() => {
    Taro.switchTab({
      url: "/pages/mine/index",
    })
  }, 1500)
  return false
}

export function throttle(fn, delay = 200) {
  let timer
  return function () {
    if (timer) return
    timer = setTimeout(() => {
      fn.apply(this, arguments)
      timer = null
    }, delay)
  }
}

export function debounce(fn, wait = 200) {
  let timeout
  return function () {
    if (timeout !== null) clearTimeout(timeout)
    timeout = setTimeout(() => {
      fn.apply(this, arguments)
    }, wait)
  }
}

export function getLaunchIsEmbedded() {
  const option = Taro.getEnterOptionsSync()
  return option.apiCategory === "embedded"
}
export function getLaunchOptionsSync() {
  const option = Taro.getLaunchOptionsSync()
  return option
}

export async function setStorageUserInfo() {
  const { data } = await Http.get("/covid19/manage/user/info")
  Taro.setStorageSync("userInfo", data)
}

export function getStorageUserInfo() {
  return Taro.getStorageSync("userInfo")
}

export function getCacheWxCode(): any {
  try {
    let s = Taro.getStorageSync("CacheWxCode")
    if (s != null && s.length > 0) {
      let { code = null, timestamp = null } = JSON.parse(s)
      let isExpired = true
      let max = 5 * 60 * 1000 //有效期5分钟
      let now = new Date().getTime()
      if (timestamp != null) {
        if (now - timestamp > max) {
          isExpired = false
          code = null
        }
      }
      return {
        isExpired,
        code,
      }
    }
  } catch (e) {}
  return {
    isExpired: true,
    code: null,
  }
}

export function setCacheWxCode(code) {
  Taro.setStorageSync(
    "CacheWxCode",
    JSON.stringify({
      timestamp: new Date().getTime(),
      code: code,
    })
  )
}

export function formatNumber(n: Number | any, pricise = 1): Number | any {
  if (n == null) {
    return n
  }
  //保留1位小数
  return (n * 1.0).toFixed(pricise)
}

// 获取首页引导状态
export function homeGuideStatus() {
  return Taro.getStorageSync("homeGuideStatus")
}

// 设置首页引导状态
export function setHomeGuideStatus() {
  Taro.setStorageSync("homeGuideStatus", 1)
}

// 获取查一查引导状态
export function searchGuideStatus() {
  return Taro.getStorageSync("searchGuideStatus")
}

// 设置查一查引导状态
export function setSearchGuideStatus() {
  Taro.setStorageSync("searchGuideStatus", 1)
}

// 获取查一查引导状态
export function getScrollTop() {
  return Taro.getStorageSync("scroll_top")
}
// 设置查一查引导状态
export function setScrollTop() {
  Taro.setStorageSync("scroll_top", 1)
}
export function clearScrollTop() {
  Taro.removeStorageSync("scroll_top")
}
export function subscribeMessage(subscribeType: "now" | "last") {
  return new Promise(resolve => {
    const tmplIds = ["HevaJUvAFF0M6pib2M26XN7udHGA8WISv9s3vlWGiC0"]
    if (subscribeType !== "now") {
      tmplIds.push("Do3Y0FjxwDz1Wvwh9TRRKymVanCn6xeA-J3OrUEL770")
    }
    Taro.requestSubscribeMessage({
      tmplIds,
      success: function (res) {
        resolve(res)
      },
      fail: res => {
        resolve(res)
      },
    })
  })
}

export function saveChatBloodSuger(v: any) {
  Taro.setStorageSync("ChatBloodSuger", v)
}

export function restoreChatBloodSuger() {
  return Taro.getStorageSync("ChatBloodSuger")
}

export function saveMedicalHistoryAccess() {
  Taro.setStorageSync("MedicalHistoryAccess", "YES")
}

export function enableMedicalHistoryAccess() {
  let a = Taro.getStorageSync("MedicalHistoryAccess")
  return a != "YES"
}
// 判断是否已经绑定SN码
export const checkIsBinding = async () => {
  const { data } = await Http.get("/diet/device/bind/verification")
  return data?.flag
}
// 判断是否已经完成基线
export const checkBaselineIsComplete = async () => {
  const { data } = await Http.get("/diet/user/baseline/isComplete")
  return data?.flag
}

export function setRoutingPath(path) {
  Taro.setStorageSync("routingPath", path)
}
export function getRoutingPath() {
  return Taro.getStorageSync("routingPath")
}
export function removeRoutingPath() {
  return Taro.removeStorageSync("routingPath")
}

//根据传入日期，获取该日期的上一周
export function getLastWeekFn() {
  let today = new Date()
  //构建当前日期,格式：2022-08-22 00:00:00
  let year = today.getFullYear() //本年
  let month = today.getMonth() + 1 //本月
  let day = today.getDate() //本日
  let newDate = new Date(year + "-" + month + "-" + day + " 00:00:00") //年月日拼接

  let nowTime = newDate.getTime() //当前的时间戳
  let weekDay = newDate.getDay() //当前星期 0.1.2.3.4.5.6 【0 = 周日】

  let oneDayTime = 24 * 60 * 60 * 1000 //一天的总ms

  // 当前星期减去天数，如今天为周五，则本周一为周五的时间戳减去4天的时间戳。但周日特殊，周一至周六是周几的到的weekDay就是几，但是周日的到的为0，需特殊处理
  let thisWeekMondayTime = (1 - weekDay) * oneDayTime + nowTime //本周一的时间戳
  if (weekDay == 0) {
    // weekDay = 0 为周日，此时本周一时间为周日减去6天的时间
    thisWeekMondayTime = nowTime - 6 * oneDayTime
  }
  let lastWeekMondayTime = thisWeekMondayTime - 7 * oneDayTime // 上周一
  let lastWeekSundayTime = thisWeekMondayTime - oneDayTime // 上周日

  return dateToMMDD(lastWeekMondayTime) + "~" + dateToMMDD(lastWeekSundayTime)
}
export function dateToMMDD(date) {
  let time = new Date(date)
  let m: any = time.getMonth() + 1
  m = m > 9 ? m : "0" + m
  let d: any = time.getDate()
  d = d > 9 ? d : "0" + d

  return m + "月" + d + "日"
}

/*
 * 获取当前日期的后一天
 */
function getDays(date) {
  let fmt = "-"
  let currentDate = new Date(date)
  let y = currentDate.getFullYear()
  let m = currentDate.getMonth() + 1
  let d = currentDate.getDate()
  if (d + 1 > new Date(y, m, 0).getDate()) {
    if (m + 1 > 12) {
      y = y + 1
      m = 1
      d = 1
    } else {
      m = m + 1
      d = 1
    }
  } else {
    d = d + 1
  }
  let nextDate = new Date(`${y}-${m}-${d}`)
  let Y = new Date(nextDate).getFullYear()
  let M = new Date(nextDate).getMonth() + 1
  let D = new Date(nextDate).getDate()
  return `${Y}${fmt}${M}${fmt}${D}`
}

function getDiffDay(date_1, date_2) {
  // 计算两个日期之间的所有日期
  let totalDays, diffDate
  let myDate_1 = Date.parse(date_1)
  let myDate_2 = Date.parse(date_2)
  // 将两个日期都转换为毫秒格式，然后做差
  diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值

  totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
  let days = [date_1]
  for (let i = 0; i < totalDays; i++) {
    let nextDay = getDays(days[i])
    days.push(nextDay)
  }
  return days
}

export function getDayFromDateRange(date1, date2) {
  let diffDays = getDiffDay(date1, date2)
  let days: any[] = []
  diffDays.forEach(item => {
    let D: Number = new Date(item).getDate()
    days.push(D)
  })
  return days
}
// console.log(getDayFromDateRange('2023-6-26','2023-7-2'))

export function throttleInitial(fn, wait = 200) {
  let timeout
  return function () {
    if (timeout) return
    fn.apply(this, arguments)
    timeout = setTimeout(() => {
      timeout = null
    }, wait)
  }
}

// 把时间戳转换成 年月日时分
export function getFormatDate(time) {
  let date = new Date(time)
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hours = date.getHours()
  let minutes = date.getMinutes()
  // return `${year}-${month}-${day} ${hours}:${minutes}`
  return `${year}-${month}-${day}`
}

// 复制
export function copyText(text) {
  Taro.setClipboardData({
    data: text,
    success: function () {
      Taro.showToast({
        title: "复制成功",
        icon: "success",
        duration: 2000,
      })
    },
  })
}
